package com.beerandjesus.webapp.sportofkings.handicapper.util;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.beerandjesus.webapp.sportofkings.handicapper.struts.action.BaseAnalyzeAction.*;

/**
 * Date: 10/19/14
 * Time: 10:59 AM
 */
public class FileUtil {

    private static final Pattern RESULTS_FILE_PATTERN = Pattern.compile("^" + PARAM_RESULTS + "_([A-Z]+)_([0-9]{8})$");

    public void sortByLastModifiedDescending(File[] files) {
        if (files == null) {
            return;
        }
        Arrays.sort(files, new Comparator<File>() {
            public int compare(File file, File file2) {
                return Long.valueOf(file2.lastModified()).compareTo(file.lastModified());
            }
        });
    }

    public FilenameFilter resultsFilenameFilter() {
        return new FilenameFilter() {
            public boolean accept(File file, String s) {
                return !(file == null || s == null) &&
                        RESULTS_FILE_PATTERN.matcher(s).matches();
            }
        };
    }

    public TrackCodeRaceDate parseFileName(String fileName) {
        Matcher matcher = RESULTS_FILE_PATTERN.matcher(fileName);
        if (matcher.find()) {
            return new TrackCodeRaceDate(matcher.group(1),matcher.group(2));
        } else {
            throw new IllegalArgumentException(fileName);
        }
    }
}
